/**
 * @file DrawBoard.as
 *
 * @author db0@qq.com
 * @version 1.0.1
 * @date 2017-08-23

   example:
   var drawBoard:DrawBoard = new DrawBoard();
   drawBoard.init();
   drawBoard.x = 100;
   drawBoard.y = 100;
   addChild(drawBoard);
 */
package
{
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	public class DrawBoard extends Sprite
	{
		public var shape:Shape = new Shape();
		private var ww:int;
		private var hh:int;
		
		public function DrawBoard()
		{
			mouseChildren = false;
			init();
			
			if (stage) addevents(null);
			else addEventListener(Event.ADDED_TO_STAGE, addevents);
		}
		
		public function init(w:int = 960, h:int = 600):void
		{
			ww = w;
			hh = h;
			addChild(shape);
			clear();
		}
		
		private function addevents(e:Event):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, addevents);
			addEventListener(MouseEvent.MOUSE_DOWN, events);
			addEventListener(MouseEvent.MOUSE_UP, events);
			addEventListener(MouseEvent.MOUSE_OUT, events);
			addEventListener(MouseEvent.MOUSE_MOVE, events);
			//addEventListener(MouseEvent.MOUSE_OVER,events);
		}
		
		public function clear():void
		{
			with (shape)
			{
				graphics.clear();
				graphics.beginFill(0xffffff, 0.0);
				graphics.drawRect(0, 0, ww, hh);
				graphics.endFill();
				graphics.lineStyle(10, 0xff000000);
			}
			_hasDrawed = false;
		}
		
		private var isDrawing:Boolean = false;
		private var _hasDrawed:Boolean = false;
		
		public function get hasDrawed():Boolean
		{
			return _hasDrawed;
		}
		
		private function events(e:MouseEvent):void
		{
			if (shape.x < mouseX && mouseX < shape.x + shape.width && shape.y < mouseY && mouseY < shape.y + shape.height)
			{
			}
			else
			{
				isDrawing = false;
				return;
			}
			//logs.adds(e.type);
			switch (e.type)
			{
			case MouseEvent.MOUSE_DOWN: 
			case MouseEvent.MOUSE_OVER: 
				shape.graphics.moveTo(mouseX - 1, mouseY - 1);
				shape.graphics.lineTo(mouseX, mouseY);
				isDrawing = true;
				_hasDrawed = true;
				break;
			case MouseEvent.MOUSE_UP: 
			case MouseEvent.MOUSE_OUT: 
				isDrawing = false;
				break;
			case MouseEvent.MOUSE_MOVE: 
				if (!isDrawing)
				{
					shape.graphics.moveTo(mouseX, mouseY);
					return;
				}
				shape.graphics.lineTo(mouseX, mouseY);
				break;
			}
		}
	}
}
